import 'dart:io';

/// CreateTime 2020/4/21 16:31
/// CreateUser chen 
/// ProjectName flutter_elf
import 'package:flutter_elf/config/component_index.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:synchronized/synchronized.dart';
import 'package:path/path.dart';
class DBManager{
  static const String dbName = 'elf.db';
  static const int _VERSION = 1;
  Database _db;
  final _lock = Lock();
  static DBManager _instance = DBManager._internal();
  DBManager._internal();
  static DBManager getInstance()=>_instance;

  //创建数据库
  createDB()async{
//    var databasesPath = await getDatabasesPath();
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, dbName);
    globalPrint('数据库存储目录=====>' + path);

    if (!await Directory(dirname(path)).exists()) {
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (e) {
        globalPrint('发生错误' + e.toString());
      }
    }
    _db = await openDatabase(path,
        version: _VERSION, onCreate: (Database db, int version) async {});
  }

  Future<bool> isTableExits(String tableName) async {
    await getDB();
    var res = await _db.rawQuery(
        "select * from Sqlite_master where type = 'table' and name = '$tableName'");
    return res != null && res.isNotEmpty;
  }

  Future<Database> getDB() async {
    if (_db == null) {
      await _lock.synchronized(() async {
        // Check again once entering the synchronized block
        if (_db == null) {
          await createDB();
        }
      });
    }
    return _db;
  }

  void close() {
    _db?.close();
    _db = null;
  }

}